package com.wxm.common.file.core.service.supplier;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectRequest;
import com.wxm.common.file.core.exception.FileException;
import com.wxm.common.file.core.property.AliyunOssProperty;
import com.wxm.common.file.core.property.UploadBaseProperty;

import java.io.InputStream;

/**
 * <p>
 *       供应商[阿里云OSS文件储存]Service
 * </p>
 *
 * @author: wxm
 * @Date: 2022/1/27
 */
public class AliyunOssService implements SupplierBaseService {
    private AliyunOssProperty property;

    /**
     * 参数非空校验
     */
    private void checkProperty(){
        FileException.isNull(this.property.getEndpoint(),"Endpoint不能为null");
        FileException.isNull(this.property.getAccessKeyId(),"AccessKeyId不能为null");
        FileException.isNull(this.property.getAccessKeySecret(),"AccessKeySecret不能为null");
        FileException.isNull(this.property.getBucket(),"Bucket不能为null");
        FileException.isNull(this.property.getRootPath(),"RootPath不能为null");
    }

    @Override
    public void init(UploadBaseProperty uploadBaseProperty) {
        this.property = (AliyunOssProperty)uploadBaseProperty;
        this.checkProperty();
    }

    /**
     * 上传文档 https://help.aliyun.com/document_detail/84781.html
     * @param inputStream 流
     * @param fileName 文件名称
     * @throws Exception
     */
    @Override
    public void uploading(InputStream inputStream, String fileName) throws Exception {
        OSS oss = new OSSClientBuilder().build(this.property.getEndpoint(), this.property.getAccessKeyId(), this.property.getAccessKeySecret());
        PutObjectRequest putObjectRequest = new PutObjectRequest(this.property.getBucket(), fileName, inputStream);
        oss.putObject(putObjectRequest);//上传
        oss.shutdown();//关闭OSSClient
    }

    /**
     * 删除文档 https://help.aliyun.com/document_detail/84842.htm?spm=a2c4g.11186623.0.0.14c21cd5i2RQjK#concept-84842-zh
     * @param filePath 文件访问路径
     * @throws Exception
     */
    @Override
    public void delete(String filePath) throws Exception {
        OSS oss = new OSSClientBuilder().build(this.property.getEndpoint(), this.property.getAccessKeyId(), this.property.getAccessKeySecret());
        filePath = this.removeFilePathPrefix(filePath, this.property.getRootPath());
        oss.deleteObject(this.property.getBucket(), filePath);
        oss.shutdown();//关闭OSSClient
    }
}
